package com.pwc.conversionTool.rest;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;

import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pwc.conversionTool.Manager.SoapUIManager;
import com.pwc.conversionTool.Manager.XMLConfigImpl;
import com.pwc.conversionTool.controller.ConfigController;
import com.pwc.conversionTool.relation.xml.XMLFactory;
import com.pwc.conversionTool.relation.xml.XMLNode;

@Controller
public class SoapRest {

	private static final Logger logger = LoggerFactory.getLogger(SoapRest.class);
	
	@Autowired
	public ServletContext context;

	@RequestMapping(value = "/rest/operationMap", method = RequestMethod.GET, produces = "application/json")
	public @ResponseBody Map<String, String> getOperationMap() {
		
		Map<String, String> map =new HashMap<String, String>();
		
		try {
			if(SoapUIManager.isInitial())
			{
				map=SoapUIManager.getSoapUIClient().getOperationMap();
			}
		} catch (Exception e) {
			logger.error(" error in operationMap");
			logger.error(Arrays.toString(e.getStackTrace()));
		}
		
		return map;
	}
	
	@RequestMapping(value = "/rest/XMLNode", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody XMLNode getSimpleXMLJson(String OperationName) throws DocumentException
	{
		if(!SoapUIManager.isInitial())
		{
			SoapUIManager.settingEndpoint(XMLConfigImpl.initial(context).getEndpoint());
		}
		String xmlString=SoapUIManager.getSoapUIClient().getTemplate(OperationName);
		XMLFactory factory=new XMLFactory(xmlString);
		return factory.getRootNode();
	}
	
	
	@RequestMapping(value = "/rest/sendSoap", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE)
	public @ResponseBody String sendSoap(String data,String operation) {
		
		String resultString="";
		
		try {
			if(SoapUIManager.isInitial())
			{
				resultString=SoapUIManager.sendSoap(context,operation,data);				
			}
		} catch (Exception e) {
			logger.error(" error in sendSoap");
			logger.error(Arrays.toString(e.getStackTrace()));
		}
		
		return resultString;
	}
	
	

	


}
